package com.saikuo.service.utils;

import com.alipay.api.internal.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by shanchangyu on 16/10/24.
 */
public class StringUtil {
    private StringUtil() {
    }

    public static int[] stringtoArray(String str) {
        int ret[] = new int[str.length()];
        StringTokenizer toKenizer = new StringTokenizer(str, ",");
        int i = 0;
        while (toKenizer.hasMoreElements()) {
            ret[i++] = Integer.valueOf(toKenizer.nextToken());
        }
        return ret;
    }

    public static List<Integer> stringtoList(String str) {
        String[] d = str.split(",");
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < d.length; i++) {
            list.add(Integer.valueOf(d[i]));
        }
        return list;
    }

    public static <T> List<T> splitList(List<T> list, int pageSize, int index) {
        List<T> subList = new ArrayList<>();
        int totalCount = list.size();//总大小
        int pageCount;//总页码
        int m = totalCount % pageSize;//是否恰好整数页
        if (m > 0) {
            pageCount = totalCount / pageSize + 1;
        } else {
            pageCount = totalCount / pageSize;
        }
        if (m == 0) {
            if (pageCount >= index) {
                subList = list.subList((index - 1) * pageSize, pageSize * (index));
            }

        } else {
            if (index == pageCount) {
                subList = list.subList((index - 1) * pageSize, totalCount);
            } else if (pageCount > index) {
                subList = list.subList((index - 1) * pageSize, pageSize * (index));
            }
        }
        return subList;
    }

    public static String getEncodeContent(Map<String, String> sortedParams,String chaset) {
        StringBuffer content = new StringBuffer();
        ArrayList keys = new ArrayList(sortedParams.keySet());
        Collections.sort(keys);
        int index = 0;

        for(int i = 0; i < keys.size(); ++i) {
            String key = (String)keys.get(i);
            String value = null;
            try {
                value = URLEncoder.encode(sortedParams.get(key),chaset);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if(StringUtils.areNotEmpty(new String[]{key, value})) {
                content.append((index == 0?"":"&") + key + "=" + value);
                ++index;
            }
        }

        return content.toString();
    }

    public static int doubleToInt(Double param){
        return  param.intValue();
    }
}
